<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2017/6/23
 * Time: 14:37
 */

namespace Clients;

// 异步客户端
class ClientAsync
{
    private $client;

    public function __construct() {
        // SWOOLE_SOCK_ASYNC 异步客户端，可以使用回调函数的写法
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC );

        $this->client->on('Connect', array($this, 'onConnect'));
        $this->client->on('Receive', array($this, 'onReceive'));
        $this->client->on('Error', array($this, 'onError'));
        $this->client->on('Close', array($this, 'onClose'));
    }

    public function connect(){
        if( !$this->client->connect("127.0.0.1", 9501 , 1) ) {
            exit("connect failed. Error: {$this->client->errCode}\n");
        }
        echo "success connect\n";
    }

    public function onConnect(\swoole_client $client){


        // php cli 常量
        fwrite(STDOUT, "请输入消息:\n");
        $msg = trim(fgets(STDIN));

        // 如果服务器收到消息，有返回信息，会在onReceive回调函数接收到
        $this->client->send( $msg );

        // 这里不要轻易睡眠，如果睡眠了，就会阻塞；比如服务器发送的消息，onReceive就不会接收的到
        //sleep(3);
    }

    public function onError(\swoole_client $client){
        echo "error\n";
    }

    public function onClose(\swoole_client $client){
        echo "close\n";
    }

    public function onReceive(\swoole_client $client, string $data){
        echo "Get Message From Server:{$data}\n";
    }
}

$client = new ClientAsync();
$client->connect();
